const router = require('koa-router')()

const svgCaptcha = require('svg-captcha');
const jwt = require('jsonwebtoken');
const myKey = "zhangsan1234"
const path = require("path");
const serverUrl = 'localhost:3000'
let chapterlist = [
  {
    chapterId: 1,
    chapterTitle: "zara",
    timer: "2023-03-03"
  },
  {
    chapterId: 2,
    chapterTitle: "model",
    timer: "2023-03-03"
  },
  {
    chapterId: 3,
    chapterTitle: "startbuck",
    timer: "2023-03-03"
  }
]
function getRealUrl(filename) {
  let str = path.join(serverUrl, filename);
  console.log(str);
  let url = str.split(path.sep).join('/')
  console.log(url);
  url = 'http://' + url
  return url;
}

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

router.get('/code', async (ctx, next) => {
  var captcha = svgCaptcha.create({
    size: 4, // 验证码长度
    width: 160,
    height: 60,
    fontSize: 50,
    ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1i
    noise: 2, // 干扰线条的数量
    color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
    background: '#eee' // 验证码图片背景颜色
  }
  )
  ctx.session.captcha = captcha.text
  setTimeout(() => {
    console.log(captcha.text);
    console.log(1234566);
  }, 1000)
  ctx.body = captcha.data
})

router.post('/login', async (ctx, next) => {
  console.log(ctx.session);
  const imglist = ctx.request.body
  console.log(imglist);
  let sql = "select * from administrator"
  let result = await ctx.db.EXCUTE(sql)
  console.log(result);
  for (let i = 0; i < result.length; i++) {
    if (result[i].adminename == imglist.name &&
      result[i].adminepwd == imglist.pwd &&
      imglist.test.toString() == ctx.session.captcha) {
      console.log('success');
      let token = jwt.sign({ username: imglist.name }, myKey)

      ctx.body = {
        code: 200,
        msg: 'success',
        token: token
      }
      return
    }
  }
  console.log(22222);
  ctx.body = {
    code: 200,
    msg: 'fail'
  }
})
router.post("/getdata", async (ctx, next) => {
  console.log(ctx.req.headers);
  console.log(ctx.request.body);

  // let body = JSON.parse(ctx.request.body);
  // let tokenSaved = body.token;

  let tokenSaved = JSON.parse(ctx.request.body.token).token;
  console.log("tokenSaved", +tokenSaved)

  let token = ctx.req.headers.authorization;
  let result = jwt.verify(token, myKey);



  if (tokenSaved == token) {
    ctx.body = result;
  }
  console.log("result:", result);
})
router.post('/upload', async (ctx, next) => {
  let token = ctx.request.body.token
  console.log(token);
  let sql = "select * from administrators"
  let result = await ctx.db.EXCUTE(sql)
  try{
    jwt.verify(token, myKey)
    let result1 = jwt.verify(token, myKey)
    for (let i = 0; i < result.length; i++) {
      if (result[i].adminname == result1.username) {
        console.log('success');
        let token = jwt.sign({ username: result[i].adminname }, myKey)
        ctx.body = {
          code: 200,
          msg: 'success',
          token: token
        }
        return
      } 
      if(i==result.length-1 && result[i].adminname != result1.username){
        ctx.body = {
          code: 200,
          msg: 'error'
        }
      }
    }
  } catch (err){
    console.log(err);
    ctx.body = {
      code: 200,
      msg: 'error'
    }
  }


})


//ctx.request.body接受http请求请求体里的数据
router.post('/sub', async (ctx, next) => {
  console.log(ctx.request.body);
  let chapter = {
    chapterId: Math.random(),
    chapterTitle: ctx.request.body.chapterTitle,
    timer: ctx.request.body.timer
  }
  chapterlist.push(chapter);
  //告诉前端数据我已经收到，操作完成
  ctx.body = 'ok';
})

router.post('/del', async (ctx, next) => {
  console.log(ctx.request.body);
  let id = ctx.request.body.id;
  let index = '';
  for (let i = 0; i < chapterlist.length; i++) {
    if (chapterlist[i]['chapterId'] == id) {
      index = i;
    }
  }
  chapterlist.splice(index, 1);
  ctx.body = 'success';
})

router.post('/subform', async (ctx, next) => {
  let chapterTitle = ctx.request.body.chapterTitle;
  let timer = ctx.request.body.timer;

  let dataObj = new Date(timer);
  timer = dataObj.getFullYear() + "-" + dataObj.getMonth() + "-" + dataObj.getDate();
  console.log(chapterTitle, timer);
  let chapter = {
    chapterId: Math.random(),
    chapterTitle: chapterTitle,
    timer: timer
  }
  chapterlist.unshift(chapter);
})


// //动态生成验证码
// router.get('/code', async (ctx, next) => {

//   const cap = svgCaptcha.create({
//     size: 4, // 验证码长度
//     width:160,
//     height:60,
//     fontSize: 50,
//     ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1i
//     noise: 2, // 干扰线条的数量
//     color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
//     background: '#eee' // 验证码图片背景颜色
//   })

//   let img = cap.data // 验证码
//   let text = cap.text.toLowerCase() // 验证码字符，忽略大小写

//   // 设置响应头
//   ctx.response.type = 'image/svg+xml';

//   ctx.body = img;
// });
// 获取某商品下的评论
router.post('/goodscomment/getcomment', async (ctx, next) => {
  console.log(ctx.request.body);
  let commodityid = ctx.request.body.commodityid;
  console.log(commodityid);
  let result = await ctx.db.EXCUTE("select * from goodscomment where commodityid=" + commodityid);
  for (let i = 0; i < result.length; i++) {
    result[i].commentimgs = await ctx.db.EXCUTE("select * from commentimg where comment_id=" + result[i].comment_id);
    result[i].avatar = await ctx.db.EXCUTE("select avatar from user where userid=" + result[i].userid);
  }
  console.log(result);
  ctx.body = {
    code: 200,
    data: result
  }
})
module.exports = router
